package com.weslide.weslideapp.util;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.os.AsyncTask;
import android.util.Log;
import android.view.KeyEvent;

import com.gt.cl.http.CLConnectionException;
import com.gt.cl.http.CLInvalidNetworkException;
import com.weslide.weslideapp.R;

public abstract class TMTPAsyncTask<Params, Progress, Result> extends
		AsyncTask<Params, Progress, Object> {

	private static final String tag = "CommonAsyncTask";
	private Params p;
	private boolean isShowLoading = true;
	private boolean canCloseLoading = false;
	private Activity context;
	private ProgressDialog progressDialog;
	private AlertDialog alertDialog;

	private static boolean isShowlingDialog;

	public TMTPAsyncTask(Activity context) {
		this(context, true);
	}

	public TMTPAsyncTask(Activity context, boolean isShowLoading) {
		this.context = (Activity) TMTPUtil.getMainContext(context);
		this.isShowLoading = isShowLoading;
	}

	public TMTPAsyncTask(Activity context, boolean isShowLoading,
			boolean canClosLoading) {
		this.context = (Activity) TMTPUtil.getMainContext(context);
		this.isShowLoading = isShowLoading;
		this.canCloseLoading = canClosLoading;
	}

	@Override
	protected void onCancelled() {
		if (isShowLoading && !canCloseLoading) {
			closeLoading();
		}
		super.onCancelled();
	}

	protected Activity getContext() {
		return context;
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		if (isShowLoading) {
			this.showLoading(canCloseLoading);
		}
	}

	@Override
	protected Object doInBackground(Params... params) {
		Object obj = null;
		p = null;
		if (params != null && params.length > 0) {
			p = params[0];
		}
		try {
			obj = this.doInBackground(p);
		} catch (Exception e) {
			obj = e;
		}
		return obj;
	}

	protected boolean handleException(Exception ex) {
		return true;
	}

	@Override
	protected void onPostExecute(Object result) {
		Log.i(tag, "result  >>>>   " + result);
		try {
			super.onPostExecute(result);
			if (result != null) {
				if (result instanceof CLInvalidNetworkException) {
					boolean isHandled = this
							.handleException((CLInvalidNetworkException) result);
					if (isHandled) {
						this.showAlert("网络连接失败");
					}
					Log.e(tag, "", (Exception) result);
				} else if (result instanceof CLConnectionException) {
					CLConnectionException connectionException = (CLConnectionException) result;
					boolean isHandled = this
							.handleException(connectionException);
					if (isHandled) {
						this.showAlert("服务器忙");
					}
					Log.e(tag, "", (Exception) result);
				} else if (result instanceof Exception) {
					boolean isHandled = this
							.handleException((Exception) result);
					if (!isHandled) {
						this.showAlert(((Exception) result).getMessage());
					}
					Log.e(tag, "", (Exception) result);
				} else {
					onFinishHandle();
					doOnSuccess((Result) result);
				}
			} else {
				onFinishHandle();
				doOnSuccess((Result) result);
			}
		} catch (Exception e) {
			Log.e(tag, "", e);
		} finally {
			if (progressDialog != null) {
				progressDialog.cancel();
			}
		}

	}

	abstract protected Result doInBackground(Params params)
			throws CLInvalidNetworkException, CLConnectionException;

	abstract protected void doOnSuccess(Result result);

	protected void doOnResponseOKButton(String status) {
	}

	private void showLoading(boolean canCloseDialog) {
		if (progressDialog == null) {
			progressDialog = new ProgressDialog(context);
			progressDialog.setTitle(R.string.app_name);
			progressDialog.setMessage("加载中");
			progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progressDialog.setCanceledOnTouchOutside(false);
			progressDialog.setCanceledOnTouchOutside(false);
			if (!canCloseDialog) {
				progressDialog.setOnKeyListener(new OnKeyListener() {
					@Override
					public boolean onKey(DialogInterface dialog, int keyCode,
							KeyEvent event) {
						if (keyCode == KeyEvent.KEYCODE_BACK
								&& event.getRepeatCount() == 0) { // 按下的如果是BACK，同时没有重复
							return true;
						}
						return false;

					}
				});
			}

		}

		progressDialog.show();
	}

	private void closeLoading() {

		if (progressDialog != null) {
			try {
				progressDialog.hide();
				progressDialog.cancel();
				progressDialog = null;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private void showAlert(String errorMsg) {
		showAlert(errorMsg, null);
	}

	private void showAlert(String errorMsg, final String status) {
		if (!isShowlingDialog) {
			isShowlingDialog = true;
			AlertDialog.Builder builder = new AlertDialog.Builder(context);
			builder.setIcon(android.R.drawable.stat_notify_error);
			builder.setTitle(context.getString(R.string.app_name));
			builder.setMessage(errorMsg);
			builder.setNeutralButton("是",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface d, int whichButton) {
							onFinishHandle();
							d.cancel();
							doOnResponseOKButton(status);
							isShowlingDialog = false;
						}
					});

			alertDialog = builder.create();
			alertDialog.setCanceledOnTouchOutside(false);
			alertDialog.setOnKeyListener(new OnKeyListener() {
				@Override
				public boolean onKey(DialogInterface dialog, int keyCode,
						KeyEvent event) {
					if (keyCode == KeyEvent.KEYCODE_BACK
							&& event.getRepeatCount() == 0) { // 按下的如果是BACK，同时没有重复
						isShowlingDialog = false;
						return true;
					}
					return false;
				}
			});

			alertDialog.show();
		}
	}

	protected void onFinishHandle() {
	}
}
